package cn.xzqwjw.taskmanager.security;

import cn.xzqwjw.taskmanager.security.filter.AuthLoginAdminFilter;
import cn.xzqwjw.taskmanager.security.handler.LoginFailedJwtHandler;
import cn.xzqwjw.taskmanager.security.handler.LoginSuccessAdminHandler;
import cn.xzqwjw.taskmanager.service.LogLoginService;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.web.HttpSecurityBuilder;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.web.authentication.logout.LogoutFilter;
import org.springframework.security.web.authentication.session.NullAuthenticatedSessionStrategy;

/**
 * @author rush
 */
public class LoginAuthAdminConfig<T extends LoginAuthAdminConfig<T, B>,
    B extends HttpSecurityBuilder<B>>
    extends AbstractHttpConfigurer<T, B> {

  private final AuthLoginAdminFilter authLoginAdminFilter;

  private final LogLoginService logLoginService;

  public LoginAuthAdminConfig(LogLoginService logLoginService) {
    this.authLoginAdminFilter = new AuthLoginAdminFilter();
    this.logLoginService = logLoginService;
  }

  @Override
  public void configure(B http) {
    // 设置 Filter 使用的 AuthenticationManager，这里取公共的即可
    authLoginAdminFilter.setAuthenticationManager(http.getSharedObject(AuthenticationManager.class));
    // 设置验证成功的 handler
    authLoginAdminFilter.setAuthenticationSuccessHandler(new LoginSuccessAdminHandler(logLoginService));
    // 设置验证失败的 handler
    authLoginAdminFilter.setAuthenticationFailureHandler(new LoginFailedJwtHandler());
    // 设置 session 管理器为空，不将认证后的 context 放入 session
    authLoginAdminFilter.setSessionAuthenticationStrategy(new NullAuthenticatedSessionStrategy());
    // 定义 AuthUsernamePasswordFilter 过滤器
    AuthLoginAdminFilter filter = postProcess(authLoginAdminFilter);
    // 将过滤器放入过滤链中，并指定Filter的位置，将 filter 放到 LogoutFilter 之后
    http.addFilterAfter(filter, LogoutFilter.class);
  }

}
